package com.qianxun.module.datasource1.common.service;

import com.qianxun.module.datasource1.common.constant.EhCacheKeyName;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * @author: huwei
 * @date: 2019/12/30 10:04
 * @version: 1.0.0
 */
@Service
public class EhcacheService {
    @Resource
    private EhCacheCacheManager ehCacheCacheManager;

    public <T extends Serializable> T putInGlobal(String key , T obj ){
        return put(EhCacheKeyName.global ,key ,obj);
    }

    public <T extends  Serializable> T put(EhCacheKeyName systemCacheName , String key , T obj){
        ehCacheCacheManager.getCache(systemCacheName.name()).put(key ,obj);
        return obj;
    }

    public <T extends  Serializable> T getInGlobal(String key){
        return get(EhCacheKeyName.global ,key);
    }

    public <T extends  Serializable> T get(EhCacheKeyName systemCacheName, String key){
        Cache cache = ehCacheCacheManager.getCache(systemCacheName.name());
        Object obj = cache.get(key);
        if(obj == null){
            return null;
        }
        if(SimpleValueWrapper.class.isAssignableFrom(obj.getClass())){
            return (T) ((SimpleValueWrapper)obj).get();
        }
        return (T)obj;
    }

    public void deleteInGlobal(String key){
        delete(EhCacheKeyName.global ,key);
    }

    public void delete(EhCacheKeyName systemCacheName , String key){
        Cache cache = ehCacheCacheManager.getCache(systemCacheName.name());
        cache.evict(key);
    }
}
